#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
桌面小部件 - 悬浮在桌面上的快捷操作面板
参考360桌面助手的设计理念
"""

import tkinter as tk
from tkinter import ttk, messagebox
import os
import sys
from datetime import datetime
import threading
import time
import subprocess

class DesktopWidget:
    def __init__(self):
        self.root = tk.Tk()
        self.setup_window()
        self.setup_ui()
        self.setup_hover_effect()
        self.is_expanded = False
        self.is_dragging = False
        self.drag_data = {"x": 0, "y": 0}
        
    def setup_window(self):
        """设置窗口属性"""
        self.root.title("桌面助手")
        self.root.geometry("60x200+50+50")  # 初始大小和位置
        self.root.configure(bg='#2c3e50')
        
        # 设置窗口属性
        self.root.overrideredirect(True)  # 去掉窗口边框
        self.root.attributes('-topmost', True)  # 始终在最前面
        self.root.attributes('-alpha', 0.9)  # 透明度
        
        # 设置窗口可拖拽
        self.root.bind('<Button-1>', self.start_drag)
        self.root.bind('<B1-Motion>', self.on_drag)
        self.root.bind('<ButtonRelease-1>', self.stop_drag)
        
        # 鼠标悬停效果
        self.root.bind('<Enter>', self.on_enter)
        self.root.bind('<Leave>', self.on_leave)
        
    def setup_ui(self):
        """设置用户界面"""
        # 主容器
        self.main_frame = tk.Frame(self.root, bg='#2c3e50')
        self.main_frame.pack(fill='both', expand=True, padx=2, pady=2)
        
        # 标题栏
        self.title_frame = tk.Frame(self.main_frame, bg='#34495e', height=30)
        self.title_frame.pack(fill='x', pady=(0, 5))
        self.title_frame.pack_propagate(False)
        
        # 标题
        self.title_label = tk.Label(self.title_frame, text="桌面助手", 
                                   font=('微软雅黑', 10, 'bold'),
                                   fg='white', bg='#34495e')
        self.title_label.pack(side='left', padx=5, pady=5)
        
        # 最小化/展开按钮
        self.toggle_btn = tk.Button(self.title_frame, text="─", 
                                   font=('微软雅黑', 8, 'bold'),
                                   fg='white', bg='#34495e', 
                                   relief='flat', width=2, height=1,
                                   command=self.toggle_expand)
        self.toggle_btn.pack(side='right', padx=2, pady=2)
        
        # 关闭按钮
        self.close_btn = tk.Button(self.title_frame, text="×", 
                                  font=('微软雅黑', 8, 'bold'),
                                  fg='white', bg='#e74c3c', 
                                  relief='flat', width=2, height=1,
                                  command=self.close_widget)
        self.close_btn.pack(side='right', padx=2, pady=2)
        
        # 功能按钮区域
        self.buttons_frame = tk.Frame(self.main_frame, bg='#2c3e50')
        self.buttons_frame.pack(fill='both', expand=True)
        
        # 时钟显示
        self.clock_label = tk.Label(self.buttons_frame, 
                                   font=('微软雅黑', 12, 'bold'),
                                   fg='#ecf0f1', bg='#2c3e50')
        self.clock_label.pack(pady=5)
        
        # 快捷按钮
        self.create_quick_buttons()
        
        # 启动时钟更新
        self.update_clock()
        
    def create_quick_buttons(self):
        """创建快捷按钮"""
        buttons_config = [
            ("🔍", "扫描桌面", self.scan_desktop),
            ("✨", "一键整理", self.organize_desktop),
            ("📁", "收纳空间", self.open_storage),
            ("🖥️", "打开助手", self.open_main_app),
            ("🗑️", "清理垃圾", self.clean_temp),
        ]
        
        for icon, tooltip, command in buttons_config:
            btn = tk.Button(self.buttons_frame, text=icon, 
                           font=('微软雅黑', 16),
                           fg='white', bg='#3498db',
                           relief='flat', width=3, height=1,
                           command=command)
            btn.pack(pady=2, padx=5)
            
            # 添加悬停提示
            self.create_tooltip(btn, tooltip)
            
    def create_tooltip(self, widget, text):
        """创建悬停提示"""
        def on_enter(event):
            tooltip = tk.Toplevel()
            tooltip.wm_overrideredirect(True)
            tooltip.wm_geometry(f"+{event.x_root+10}+{event.y_root+10}")
            tooltip.configure(bg='black')
            
            label = tk.Label(tooltip, text=text, 
                           font=('微软雅黑', 9),
                           fg='white', bg='black',
                           relief='solid', borderwidth=1)
            label.pack()
            
            def on_leave(event):
                tooltip.destroy()
            
            tooltip.bind('<Leave>', on_leave)
            widget.bind('<Leave>', on_leave)
            
        widget.bind('<Enter>', on_enter)
        
    def setup_hover_effect(self):
        """设置悬停效果"""
        def on_enter_widget(event):
            self.root.attributes('-alpha', 1.0)
            
        def on_leave_widget(event):
            self.root.attributes('-alpha', 0.9)
            
        self.root.bind('<Enter>', on_enter_widget)
        self.root.bind('<Leave>', on_leave_widget)
        
    def update_clock(self):
        """更新时钟显示"""
        now = datetime.now()
        time_str = now.strftime("%H:%M")
        date_str = now.strftime("%m/%d")
        
        self.clock_label.config(text=f"{time_str}\n{date_str}")
        
        # 每秒更新一次
        self.root.after(1000, self.update_clock)
        
    def toggle_expand(self):
        """切换展开/收缩状态"""
        if self.is_expanded:
            # 收缩
            self.root.geometry("60x200")
            self.toggle_btn.config(text="─")
            self.is_expanded = False
        else:
            # 展开
            self.root.geometry("120x250")
            self.toggle_btn.config(text="□")
            self.is_expanded = True
            
    def start_drag(self, event):
        """开始拖拽"""
        self.is_dragging = True
        self.drag_data["x"] = event.x
        self.drag_data["y"] = event.y
        
    def on_drag(self, event):
        """拖拽中"""
        if self.is_dragging:
            x = (event.x_root - self.drag_data["x"])
            y = (event.y_root - self.drag_data["y"])
            self.root.geometry(f"+{x}+{y}")
            
    def stop_drag(self, event):
        """停止拖拽"""
        self.is_dragging = False
        
    def on_enter(self, event):
        """鼠标进入"""
        self.root.attributes('-alpha', 1.0)
        
    def on_leave(self, event):
        """鼠标离开"""
        self.root.attributes('-alpha', 0.8)
        
    def scan_desktop(self):
        """扫描桌面"""
        desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
        try:
            files = [f for f in os.listdir(desktop_path) 
                    if os.path.isfile(os.path.join(desktop_path, f))]
            messagebox.showinfo("扫描结果", f"桌面共有 {len(files)} 个文件")
        except Exception as e:
            messagebox.showerror("错误", f"扫描失败: {str(e)}")
            
    def organize_desktop(self):
        """一键整理桌面"""
        result = messagebox.askyesno("确认", "确定要整理桌面吗？")
        if result:
            try:
                # 启动主程序的整理功能
                script_path = os.path.join(os.path.dirname(__file__), "desktop_helper.py")
                subprocess.Popen([sys.executable, script_path])
                messagebox.showinfo("提示", "已启动桌面整理程序")
            except Exception as e:
                messagebox.showerror("错误", f"启动失败: {str(e)}")
                
    def open_storage(self):
        """打开收纳空间"""
        storage_path = os.path.join(os.path.dirname(__file__), "桌面收纳空间")
        try:
            if os.path.exists(storage_path):
                os.startfile(storage_path)
            else:
                messagebox.showinfo("提示", "收纳空间不存在，请先进行桌面整理")
        except Exception as e:
            messagebox.showerror("错误", f"打开失败: {str(e)}")
            
    def open_main_app(self):
        """打开主程序"""
        try:
            script_path = os.path.join(os.path.dirname(__file__), "desktop_helper.py")
            subprocess.Popen([sys.executable, script_path])
        except Exception as e:
            messagebox.showerror("错误", f"启动失败: {str(e)}")
            
    def clean_temp(self):
        """清理临时文件"""
        try:
            temp_paths = [
                os.path.join(os.environ.get('TEMP', ''), '*'),
                os.path.join(os.environ.get('TMP', ''), '*'),
                os.path.join(os.path.expanduser("~"), "AppData", "Local", "Temp", '*')
            ]
            
            cleaned_count = 0
            for path in temp_paths:
                if os.path.exists(os.path.dirname(path)):
                    try:
                        import glob
                        files = glob.glob(path)
                        for file in files:
                            if os.path.isfile(file):
                                try:
                                    os.remove(file)
                                    cleaned_count += 1
                                except:
                                    pass
                    except:
                        pass
            
            messagebox.showinfo("清理完成", f"已清理 {cleaned_count} 个临时文件")
        except Exception as e:
            messagebox.showerror("错误", f"清理失败: {str(e)}")
            
    def close_widget(self):
        """关闭小部件"""
        result = messagebox.askyesno("确认", "确定要关闭桌面小部件吗？")
        if result:
            self.root.destroy()
            
    def run(self):
        """运行小部件"""
        self.root.mainloop()

if __name__ == "__main__":
    widget = DesktopWidget()
    widget.run() 